package database;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Map;

public class DataManager {

	public static ArrayList<String> fileNameInMemory = new ArrayList<String>();
	public static ArrayList<DataFile> fileInMemory = new ArrayList<DataFile>();

	public static DataFile createFile(String fileName,
			Map<String, Integer> descriptor) throws IllegalArgumentException {
		if (!fileNameInMemory.contains(fileName)) {
			DataFile dataFile = new DataFile(fileName, descriptor);
			fileNameInMemory.add(fileName);
			fileInMemory.add(dataFile);
			return dataFile;
		} else {
			throw new IllegalArgumentException();
		}
	}

	public static DataFile restoreFile(String fileName)
			throws IllegalArgumentException {
		FileInputStream is;
		try {
			if (!fileNameInMemory.contains(fileName)) {
				is = new FileInputStream(fileName);
				ObjectInputStream ois = new ObjectInputStream(is);
				DataFile df = (DataFile) ois.readObject();
				ois.close();
				/*
				Map<Integer, Map<String, String>> map = df.getRecords();
				for (Map.Entry<Integer, Map<String, String>> item : map
						.entrySet()) {
					item.getValue().put("recordId", item.getKey().toString());
					item.getValue().put("isDel", "0");
				}
				df.setRecords(map);
				*/
				return df;
			} else {
				throw new IllegalArgumentException();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			throw new IllegalArgumentException();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public static String print(Map<String, String> record) {
		String result = "";
		for (Map.Entry<String, String> em : record.entrySet()) {
			if (em.getValue() != null) {
				result += em.getKey() + ":  " + em.getValue() + "\n";
			}
		}
		return result;
	}

	public static void exit() {
		fileNameInMemory.clear();
	}
}
